<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/20
 * Time: 11:20
 */

namespace app\admin\controller;

use app\model\UserInfo as ModelUserInfo;
use app\model\UserOrder as ModelUserOrder;
use app\model\UserOrderLog as ModelUserOrderLog;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\StationOrder as ModelStationOrder;
use app\model\Express as ModelExpress;
use app\model\DriverOrder as ModelDriverOrder;
use app\logic\Excel as MobileLogicExcel;
use app\model\UserAddress as ModelUserAddress;

class UserDetails extends User
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员详情
     * uri:/admin/user.details
     */

    public function MemberDetails(){
        $arr_where = [];

        $userId = $this->_getContentParams('userId');
        //$userId = 1;
        if (!empty($userId)){
            $arr_where['user_info.user_id'] = $userId;
        }
        $block = $this->_getContentParams('block');
        //$block = 1;
        switch ($block){
            case 1://会员详情
                $list = ModelUserInfo::getInstance()->getUserDetailList($arr_where);
                _returnData(['userDetails'=>$list]);
                break;
            case 2://统计信息
                $list = ModelUserInfo::getInstance()->getStatistical($arr_where);
                _returnData(['statistical'=>$list]);
                break;
            case 3://实名认证材料
                $list = ModelUserInfo::getInstance()->getCertification($arr_where);
                _returnData(['certification'=>$list]);
                break;
            case 4://寄件人地址簿
                $arr_where['user_address.type'] = 'send';
                $list = ModelUserInfo::getInstance()->getSendAddress($arr_where);
                _returnData(['sendAddress'=>$list]);
                break;
            case 5://收件人地址簿
                $arr_where['user_address.type'] = 'receive';
                $list = ModelUserInfo::getInstance()->getReceiveAddress($arr_where);
                _returnData(['receiveAddress'=>$list]);
                break;
            default:
                break;
        }

    }

    /**
     * 会员订单列表
     * uri:/admin/user.orderList
     */
    public function orderList(){
        $userId = $this->_getContentParams('userId');
        _toValidate('id',$userId,10009);
        //$userId =1;

        $int_now_page = $this->_getContentParams('page'); // 当前页码
        if (empty($int_now_page)){
            $int_now_page = 1;
        }
        _toValidate('id', $int_now_page, 10005);

        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        if (empty($int_list_rows)){
            $int_list_rows = 10;
        }
        _toValidate('id', $int_list_rows, 10006);
        $sort = $this->_getContentParams('sort');
        _toCompare(empty($sort),'==',true,20012);

        if (!empty($userId)){
            $arr_where['user_info.user_id'] = $userId;
        }
        $arr_where="user_order.user_id=$userId";
        $orderNumber = $this->_getContentParams('orderNumber');
        $startTime = $this->_getContentParams('startTime');
        $endTime = $this->_getContentParams('endTime');
        if(!empty($orderNumber)){
            $arr_where.=" and (user_order.order_sn like '%$orderNumber%' or user_order.express_order_sn like '%$orderNumber%')";
        }

        if (!empty($startTime)){
            $arr_where.=" and DATE_FORMAT(user_order.gmt_create,'%Y%m%d') >= DATE_FORMAT('$startTime','%Y%m%d')";
        }

        if (!empty($endTime)){
            $arr_where.=" and DATE_FORMAT(user_order.gmt_create,'%Y%m%d') <= DATE_FORMAT('$endTime','%Y%m%d')";
        }

        $int_total_rows = ModelUserOrder::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询

        $list = ModelUserOrder::getInstance()->getOrderList($arr_where,$int_first_row,$int_list_rows,$sort);
        foreach ($list as $key=>$value){
            if ($value['orderState']==0){
                $list[$key]['stateName']='已取消';
            }elseif ($value['orderState']==10 or $value['orderState']==25){
                $list[$key]['stateName']='待支付';
            }elseif ($value['orderState']==20){
                $list[$key]['stateName']='待取件';
            }elseif ($value['orderState']>=30){
                $list[$key]['stateName']='已完成';
            }
        }
        _returnData(['totalPages' => $int_total_pages,'userInfoList'=>$list]);
    }

    /**
     * 会员资料编辑
     * uri:/admin/user.editData
     */
    public function editData(){
        $userId = $this->_getContentParams('userId');
        _toValidate('id',$userId,12089);
        //$userId =1;
        $arr_where['user_info.user_id'] = $userId;
        $list = ModelUserInfo::getInstance()->getEditData($arr_where);
        _returnData(['editData'=>$list]);
    }

    /**
     * 会员订单详情
     * uri:/admin/user.orderDetails
     */
    public function userOrderDetails(){
        $orderState=null;
        $orderUserInfo=null;
        $costInformation=null;
        $basicInfo=null;
        $closed=null;
        $putInStorage=null;
        $driverInfo=null;
        $outbound=null;
        $send=null;
        $operationInfo=null;
        $orderId = $this->_getContentParams('orderId');
        //$orderId = 174;
        _toValidate('id',$orderId,10009);
        $arr_where=['user_order.order_id'=>$orderId];
        //订单状态
        $orderState = ModelUserOrder::getInstance()->toValue("order_id=$orderId",'order_state');
        if ($orderState==0){
            $orderState='已取消';
        }elseif ($orderState==10 or $orderState==25){
            $orderState='待支付';
        }elseif ($orderState==20){
            $orderState='待取件';
        }elseif ($orderState>=30){
            $orderState='已完成';
        }
        //下单人信息
        $orderUserInfo = ModelUserOrder::getInstance()->getUserOrderInfo($arr_where);
        //费用信息
        $costInformation = ModelUserOrder::getInstance()->toFind("order_id=$orderId",'first_heavy_fee AS firstHeavyFee,other_heavy_fee AS otherHeavyFee,protect_price AS protectPrice,order_amount AS orderAmount');
        //基本信息
        $basicInfo = ModelUserOrder::getInstance()->toFind("order_id=$orderId",'order_sn AS orderSn,express_order_sn AS expressOrderSn,gmt_create AS gmtCreate,door_time AS doorTime,item_price AS itemPrice,item_type AS itemType,item_weight AS itemWeight,package,sender_info AS senderInfo,recipient_info AS recipientInfo');
        $basicInfo['describe'] = ModelUserOrderLog::getInstance()->toValue("order_id=$orderId",'describe','gmt_create desc');
        //收件快递员
        $closed = ModelCourierOrder::getInstance()->getCourierInfo("courier_order.order_id=$orderId and courier_order.is_pick=1");
        //派件快递员
        $send = ModelCourierOrder::getInstance()->getCourierInfo("courier_order.order_id=$orderId and courier_order.is_pick=2");
        //发件站点
        $putInStorage = ModelStationOrder::getInstance()->getStationInfo("station_order.order_id=$orderId and station_order.is_pick=1");
        if ($putInStorage){
            $courierCompanyName = ModelExpress::getInstance()->getExpressName("express_id={$putInStorage['express_id']}");
            $putInStorage['courierCompanyName']=$courierCompanyName;
            if ($putInStorage['boxOrderNumber']){
                //司机信息
                $driverInfo = ModelDriverOrder::getInstance()->getDriverInfo("driver_order.box_id={$putInStorage['boxOrderNumber']}");
                if ($driverInfo['express_id']){
                    $courierCompanyName = ModelExpress::getInstance()->getExpressName("express_id={$driverInfo['express_id']}");
                    $driverInfo['courierCompanyName'] = $courierCompanyName;
                }elseif($driverInfo){
                    $driverInfo['courierCompanyName'] ='';
                }
            }

        }
        //收件站点
        $outbound = ModelStationOrder::getInstance()->getStationInfo("station_order.order_id=$orderId and station_order.is_pick=2");
        if ($outbound['express_id']){
            $courierCompanyName = ModelExpress::getInstance()->getExpressName("express_id={$outbound['express_id']}");
            $outbound['courierCompanyName']=$courierCompanyName;
        }elseif($outbound){
            $outbound['courierCompanyName']='';
        }

        //操作信息
        $operationInfo = ModelUserOrderLog::getInstance()->toSelect("order_id=$orderId",'operator,mobile,gmt_create AS gmtCreate,pay_state AS payState,order_state_display AS orderStateDisplay,describe,order_state AS orderState,operator,remark','','','gmt_create desc');
        foreach ($operationInfo as $key=>$value){
            if ($value['orderState']>=30){
                $operationInfo[$key]['orderStateDisplay']='已完成';
            }
            if ($value['operator']==5){
                $operationInfo[$key]['describe']=$value['remark'];
            }
            unset($operationInfo[$key]['remark']);
            unset($operationInfo[$key]['orderState']);
        }
        //dump($operationInfo);die;
        _returnData(['orderState'=>$orderState,'orderUserInfo'=>$orderUserInfo,'costInformation'=>$costInformation,'basicInfo'=>$basicInfo,'closed'=>$closed,'putInStorage'=>$putInStorage,'driverInfo'=>$driverInfo,'outbound'=>$outbound,'send'=>$send,'operationInfo'=>$operationInfo]);
    }

    /**
     * 会员管理-》会员订单列表导出
     * uri:/admin/user.orderExport
     */
    public function userOrderExport(){
        $userId = $this->_getContentParams('userId');
        _toValidate('id',$userId,10009);
        $type = $this->_getContentParams('type');
        $str_excel = $this->_getContentParams('excel');
        $sort = $this->_getContentParams('sort');
        _toCompare(empty($sort),'==',true,20012);
        //$userId =1;
        $arr_where='';
        if ($type==1){
            $arr_where="user_order.user_id=$userId";
            $orderNumber = $this->_getContentParams('orderNumber');
            $startTime = $this->_getContentParams('startTime');
            $endTime = $this->_getContentParams('endTime');
            if(!empty($orderNumber)){
                $arr_where.=" and (user_order.order_sn like '%$orderNumber%' or user_order.express_order_sn like '%$orderNumber%')";
            }

            if (!empty($startTime)){
                $arr_where.=" and DATE_FORMAT(user_order.gmt_create,'%Y%m%d') >= DATE_FORMAT('$startTime','%Y%m%d')";
            }

            if (!empty($endTime)){
                $arr_where.=" and DATE_FORMAT(user_order.gmt_create,'%Y%m%d') <= DATE_FORMAT('$endTime','%Y%m%d')";
            }
        }elseif ($type==2){
            $arrOrderId = $this->_getContentParams('arrOrderId');
            $arr_where.="user_order.user_id=$userId and user_order.order_id in ($arrOrderId)";
        }
        $list = ModelUserOrder::getInstance()->getOrderList($arr_where,'','',$sort);
        foreach ($list as $key=>$value){
            if ($value['orderState']==0){
                $list[$key]['stateName']='已取消';
            }elseif ($value['orderState']==10 or $value['orderState']==25){
                $list[$key]['stateName']='待支付';
            }elseif ($value['orderState']==20){
                $list[$key]['stateName']='待取件';
            }elseif ($value['orderState']>=30){
                $list[$key]['stateName']='已完成';
            }
        }
        if($str_excel == 'excel'){
            MobileLogicExcel::getInstance()->export($list, ['orderId' => '订单ID', 'orderSn' => '订单编号', 'expressOrderSn' => '运单号','gmtCreate'=>'下单时间','orderAmount'=>'订单金额','paytype'=>'支付方式','stateName'=>'订单状态','describe'=>'状态信息'], '快递员订单'.date('Y-m-d', time()));
        }
        _returnData();
    }

    /**
     * 用户地址簿修改
     * uri:/admin/userAddress.modify
     */
    public function userAddressModify(){
        $id = $this->_getContentParams('id');
        _toValidate('id',$id,12090);
        $prov_id = $this->_getContentParams('provId');
        $prov_name = $this->_getContentParams('provName');
        $city_id = $this->_getContentParams('cityId');
        $city_name = $this->_getContentParams('cityName');
        $county_id = $this->_getContentParams('countyId');
        $county_name = $this->_getContentParams('countyName');
        $street_id = $this->_getContentParams('streetId');
        $street_name = $this->_getContentParams('streetName');
        $detail_address = $this->_getContentParams('detailAddress');
        $name = $this->_getContentParams('name');
        $phone = $this->_getContentParams('phone');
        $lng = $this->_getContentParams('lng');
        $lat = $this->_getContentParams('lat');
        $arr_where = [
            'prov_id'=>$prov_id,
            'prov_name'=>$prov_name,
            'city_id'=>$city_id,
            'city_name'=>$city_name,
            'county_id'=>$county_id,
            'county_name'=>$county_name,
            'street_id'=>$street_id,
            'street_name'=>$street_name,
            'detail_address'=>$detail_address,
            'name'=>$name,
            'phone'=>$phone,
            'lng'=>$lng,
            'lat'=>$lat
        ];
        $data=ModelUserAddress::getInstance()->toUpdate("id=$id",$arr_where);
        if ($data>0){
            _returnData();
        }
    }

    /**
     * 地址簿删除
     * uri:/admin/userAddress.delete
     */
    public function userAddressDelete(){
        $id = $this->_getContentParams('id');
        _toValidate('id',$id,12090);
        $data = ModelUserAddress::getInstance()->toDelete("id=$id");
        if ($data>0){
            _returnData();
        }

    }

    /**
     * 地址详情
     * uri:/admin/user.address
     */
    public function userAddress(){
        $id = $this->_getContentParams('id');
        _toValidate('id',$id,12090);
        $data = ModelUserAddress::getInstance()->toFind("id=$id",'id,name,phone,prov_id AS provId,prov_name AS provName,city_id AS cityId,city_name AS cityName,county_id AS countyId,county_name AS countyName,street_id AS streetId,street_name AS streetName,detail_address AS detailAddress');
        _returnData($data);
    }

}